package s;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Statement;

public class Tagging  extends HttpServlet {
	
		private static final long serialVersionUID = 1L;
		private Properties props;
		private String propsPath;
	
		@Override
		public void init(ServletConfig config) throws ServletException {
			super.init(config);
			
			this.propsPath = this.getServletContext().getRealPath("/");
			this.props = new Properties();
			try {
				props.loadFromXML(new FileInputStream(propsPath + "properties.properties"));
			} catch (FileNotFoundException e) {e.printStackTrace();} 
			catch (IOException e) {e.printStackTrace();}
	}
	
	
		@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {}
		
		@SuppressWarnings("deprecation")
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
			String filename = req.getParameter("filename");
			String t = req.getParameter("tag");
			
			LinkedList<String> tagList = new LinkedList<String>();
			boolean finish = false;
			
			while(finish == false){
					if(t.indexOf(",") == -1){
							tagList.add(URLDecoder.decode(t));
							finish = true;
					}else{
							tagList.add(URLDecoder.decode( t.substring(0, t.indexOf(", ")) ) );
							t = t.substring(t.indexOf(",")+1, t.length());
							while(t.charAt(0) == ' '){
									t = t.substring(1, t.length());
							}
					}
			}
			
			// Connection to the database
			Connection connection = null;
			Statement statement = null;
			ResultSet rs = null;
			
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection(props.getProperty("DB_URL"), props.getProperty("DB_USER"), props.getProperty("DB_PASS"));
					statement = (Statement) connection.createStatement();
					rs = statement.executeQuery("SELECT IdImg FROM img WHERE Filename = '" +filename+"';");
					
					int idImg = -1;;
					while(rs.next()){
							idImg = rs.getInt("IdImg");
//							System.out.println("IdImg = "+idImg);
					}
					
					for(int i = 0; i < tagList.size(); i++){
						statement = (Statement) connection.createStatement();
						rs = statement.executeQuery("SELECT count(*) as num FROM tag WHERE Tag = '" +tagList.get(i)+"';");
						
						int j = -1;
						while(rs.next()){
							j = rs.getInt("num");
						}
						
						
						if(j == 0){	// "tag"-table doesn't contain the tag
								statement = (Statement) connection.createStatement();
								statement.executeUpdate("INSERT INTO tag(Tag) VALUES ('" + tagList.get(i)+"');");
						}
						
						
						int idTag = -1;
						statement = (Statement) connection.createStatement();
						rs = statement.executeQuery("SELECT IdTag FROM tag WHERE Tag = '" +tagList.get(i)+"';");
						while(rs.next()){
							idTag = rs.getInt("IdTag");
						}
										
						int k = -1;
						statement = (Statement) connection.createStatement();
						rs = statement.executeQuery("SELECT count(*) as n FROM imgTag WHERE IdTag = '" +idTag+"' AND IdImg = '" + idImg + "';");			
						while(rs.next()){
								k = rs.getInt("n");
						}
						
						if(k == -1){	// The img was already tagged with this tag
							statement = (Statement) connection.createStatement();
							statement.executeUpdate("DELETE FROM tag WHERE Tag = '" +tagList.get(i)+"';");
							PrintWriter pw = res.getWriter();
							pw.print("FAIL");
							System.out.println("FAIL");
							return;
						}else
						if(k == 0){	// Let's tag the image
								statement = (Statement) connection.createStatement();
								statement.executeUpdate("INSERT INTO imgTag(IdImg, IdTag) VALUES ('" + idImg+"', '" + idTag + "');");
						}
						
					}
	
			} 
			catch (SQLException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}
			
			PrintWriter pw = res.getWriter();
			pw.print("OK");
		}
}